<template>
  <el-header class="top-nav" v-if="!isLoginRoute">
    <div class="logo">教务管理系统</div>
    <div class="user-info" >
      <el-dropdown   @command="handleCommand">
      <span class="user-avatar">{{ username.slice(0, 2) }}</span>      
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item command="detail">{{username}}</el-dropdown-item>
          <el-dropdown-item command="logout">退出登录</el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>
    </div>
  </el-header>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';
import { useUserStore } from '../stores/user';
import { useRoute } from 'vue-router';
import router from '@/router';

const userStore = useUserStore();
const username = ref(userStore.username);
const route = useRoute();
const isLoginRoute = route.fullPath === '/login';

// 监听 userStore 中 username 的变化
watch(() => userStore.username, (newValue) => {
  username.value = newValue;
});


const handleCommand = (command: string) => {
  if (command === 'logout') {
    userStore.logOut();
    router.push('/login');
  }
};
</script>

<style scoped>
.top-nav {
  background-color: #333;
  color: white;
  height: 60px;
  line-height: 60px;
  display: flex;
  justify-content: space-between;
  padding: 0 20px;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000; /* 确保导航栏在其他内容之上 */
}

.logo {
  font-size: 24px;
  font-weight: bold;
}

.user-info {
  display: flex;
  align-items: center;
  position: relative; /* 确保下拉菜单在其内部显示 */
}

.user-avatar {
  width: 40px;
  height: 40px;
  background-color: #ccc;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 10px;
}

.el-dropdown-link {
  cursor: pointer;
}
</style>